<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>

	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<script type="text/javascript" src="js/jquery-1.7.2.js"></script>
		<title>Insert title here</title>
		<style type="text/css">
			div{
				width: 500px;
				height: 600px;
				border: 2px blue solid;
			}
			p{
				margin-left: 5px;
				width: 480px;
				height: 450px;
				border: 1px red solid;
			}
		</style>
	</head>
	
	<body>
		<div>
			<p id="msg" style="overflow: auto;display: block;"><span id="loading">loading...</span></p>
			<form id="chatform">
				<table>
					<tr><td>name:</td><td><input name="username" id="username" type="text"></td></tr>
					<tr><td>content:</td><td><textarea name="content" id="content" cols="45" rows="1"></textarea></td></tr>
					<tr><td colspan="2" align="right"><input type="submit" value="submit"></td></tr>
				</table>
			</form>
		</div>
		<script type="text/javascript">
			var timestamp = 0;
			$(function(){
				updateMsg();
				$("#chatform").submit(function(){
					if(/^\s*$/g.test($("#username").val()) || /^\s*$/g.test($("#content").val())){
						alert("写点什么吧...");
						return false;
					}
					$.post(
						"ChatAjax",
						{username:$("#username").val(),content:$("#content").val(),opt:"send"},
						function(xml){
							$("#content").val("");
							addMsg(xml);
						}
					);
					return false;
				});
			});
			function updateMsg(){
				$.post(
					"ChatAjax",
					{opt:"get",time:timestamp},
					function(xml){
						$("#loading").remove();
						addMsg(xml);
					}
				);
				setTimeout("updateMsg()",4000);
			}
			function addMsg(xml){
				if($("status",xml).text()=="0") return;
				timestamp = $("ts",xml).text();
				$("#msg").empty();
				$("message",xml).each(function(){
					var author = $("author",this).text();
					var content = $("content",this).text();
					var time = $("time",this).text();
					var html = "<strong>"+time+"</strong><br>"+author+":&nbsp;&nbsp;"+content+"<br>";
					$("#msg").prepend(html);
				});
			}
		</script>
	</body>

</html>